function [epoch,badChanMap,Dat] = mappingGetBuffer(bci,duration)

% 20110215 CR wrote it


% read the header for the first time to determine number of channels and sampling rate
bciLog([],'Waiting for buffer connection ...');
[hdr,bci]=bciReadRecorderHeader(bci);

% memory allocation
nData = round((duration+1) * bci.srate);
nEpochs = round((duration+1)*bci.param.winsrate);
nPreprocChans = length(bci.preprocChan);
Dat = zeros(hdr.nChans,nData,'single');
epoch = zeros(nPreprocChans,bci.init.nFeatPerChan,nEpochs);

% estimate size
blocksize  = round(hdr.Fs *0.1); % 1s when choosing samprate

nEpochs = round((duration+10)/bci.param.winsrate * bci.srate);
badChanMap = zeros(length(bci.preprocChan),nEpochs);

% start buffer reading
[hdr,bci]=bciReadRecorderHeader(bci,'retry',1);
endsample = hdr.nSamples;
prevSample = endsample;
startSample = endsample;
dataToRead = round(duration * bci.srate);
% now run can begin
bciLog([],'Start reading buffer ...');
startTime=GetSecs;

prevTrainSample = 0;
datCount=0;
hdrReadCount=0;
epochCount = 0;
progressBar(0,1,'Acquiring...');
while prevSample<=startSample+dataToRead,
    progressBar((prevSample-startSample)/dataToRead);
    % determine number of samples available in buffer
    [hdr,bci] = bciReadRecorderHeader(bci,'retry',1);
    hdrReadCount=hdrReadCount+1;
    newsamples = (hdr.nSamples*hdr.nTrials-prevSample);
    
    if newsamples>=blocksize
        
        % determine the samples to process
        begsample  = prevSample+1;
        endsample  = prevSample+newsamples ;
        
        % remember up to where the data was read
        prevSample  = endsample;
        
        % read data segment from buffer
        Dat(:,datCount+1:datCount+newsamples) = ...
            single(bciReadRecorderData(bci, hdr, begsample, endsample));
        
        datCount=datCount+newsamples;
        
        while datCount > prevTrainSample+bci.init.nEpochLength,
            % get next block
            [ep badChan]= bciGetEpoch(bci,Dat(bci.preprocChan,prevTrainSample+1:prevTrainSample+bci.init.nEpochLength));
            epochCount = epochCount + 1;
            epoch(:,:,epochCount) = ep;
            badChanMap(:,epochCount) = badChan;
            if abs(GetSecs-startTime-(prevTrainSample+bci.init.nEpochLength)/bci.srate)>1,
                fprintf('Warning: buffer timing difference > %2.2f s\n',GetSecs-startTime-(prevTrainSample+bci.init.nEpochLength)/bci.srate);
            end
            prevTrainSample = prevTrainSample+bci.init.nWinShift;
        end
    else%if newsamples==0, %if no samples available pause to prevent "failed to create buffer" error
        pause(0.05);
    end % if new samples available
end % while true
progressBar(1.0);
Dat = Dat(:,1:datCount);
epoch = epoch(:,:,1:epochCount);
badChanMap = badChanMap(:,1:epochCount);
